package db.swing1;

import java.awt.BorderLayout;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.PreparedStatement;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class MetaDataQueryFrame extends JFrame {
	private static final String INITIAL = "physi";
	// Könnten über RessourceManager ermittelt werden
	private static final String EXECUTE_SEARCH = "Execute Search";
	private static final String ENTER_SEARCH_TERM = "Enter search term:";
	// Diese Bedienelemente müssen bekannt sein.
	private final JButton executeSqlButton = new JButton(EXECUTE_SEARCH);
	private final JTable table = new JTable();
	private final JTextField sqlInfoTextField = new JTextField();

	public MetaDataQueryFrame(final PreparedStatement stmt) {
		super("ResultSetMetaDataExample");
		buildGUI(stmt);
	}

	private void buildGUI(final PreparedStatement preparedStmt) {
		add(buildSqlEnterContent(preparedStmt), BorderLayout.NORTH);
		add(buildResultTableContent(), BorderLayout.CENTER);
		add(buildInfoContent(), BorderLayout.SOUTH);
	}

	void executeSqlSelect() {
		executeSqlButton.doClick();
	}

	private JComponent buildSqlEnterContent(final PreparedStatement stmt) {
		final JLabel enterSqlLabel = new JLabel(ENTER_SEARCH_TERM);
		final JTextField sqlCommandTextField = new JTextField(30);
		sqlCommandTextField.setText(INITIAL);
		final JPanel sqlExecutePanel = new JPanel(new BorderLayout());
		sqlExecutePanel.add(enterSqlLabel, BorderLayout.WEST);
		sqlExecutePanel.add(sqlCommandTextField, BorderLayout.CENTER);
		sqlExecutePanel.add(executeSqlButton, BorderLayout.EAST);

		executeSqlButton.addActionListener(new ExecuteSqlActionListener(
				sqlCommandTextField, sqlInfoTextField, table, stmt));
		// Zeilennummer auslesen:
		table.getSelectionModel().addListSelectionListener(
				new ListSelectionListener() {
					@Override
					public void valueChanged(final ListSelectionEvent e) {
						// sonst werden für jeden Klick 2 Events erzeugt:
						if (e.getValueIsAdjusting()) {
							return;
						}
						int selectedRow = table.getSelectedRow();
						if (selectedRow >= 0)
							System.err.println(selectedRow + 1);
					}
				});
		// nur eine Zeile markierbar:
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		return sqlExecutePanel;
	}

	private JComponent buildResultTableContent() {
		return new JScrollPane(table);
	}

	private JComponent buildInfoContent() {
		sqlInfoTextField.setEditable(false);
		return sqlInfoTextField;
	}
}